#coding=utf-8
'''
Created on 2017-06-12

@author: sandy
'''

import sys,platform,os
sys.path.append("../")
from twisted.internet import reactor
from pycommon import Daemon,LogManager
from pycommon import RemoteManager
from pycommon import Utils
from pycommon import RedisDb2
import logging
import Manager
import ServerConfig

if 'twisted.internet.reactor' not in sys.modules: 
    if platform.system() == "Linux":
        from twisted.internet import epollreactor
        epollreactor.install()  
    else:
        from twisted.internet import iocpreactor
        iocpreactor.install()

def ServerStart(isdaemon):
    logging.info("############Start Tools############")
    Manager.instance.start(RemoteManager.instance.msip,RemoteManager.instance.msport)
    RedisDb2.instance.start(ServerConfig.instance.redisdb_ip,ServerConfig.instance.redisdb_port,ServerConfig.instance.redisdb_db,ServerConfig.instance.redisdb_passwd,ServerConfig.instance.redisdb_linkcount)
    pass

def ServerStop():
    RedisDb2.instance.stop()
    Manager.instance.stop()
    pass

def daemonFunc(isdaemon):
    LogManager.instance.setupLog(RemoteManager.instance.loglevel,RemoteManager.instance.logfile,isdaemon)
    ServerConfig.instance.loadFromFile()
    ServerStart(isdaemon)
    reactor.run()
    ServerStop()

def run():
    sid, msip, msport, pidpath, logfile, loglevel, pathSelfConfig = Utils.loadDaemonConfig(ServerConfig.instance.rundir)
    RemoteManager.instance.init(sid,msip,msport,logfile, loglevel)
    Daemon.run(pidpath, daemonFunc)

if __name__ == "__main__":
    run()